<?php
/**
*
* @package ppkBB3cker
* @version $Id: parser.php 1.000 2010-03-23 15:05:00 PPK $
* @modified by PPK (c) 2010
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

/*
Project: Kinokpk.com releaser
This file is part of Kinokpk.com releaser.
Kinokpk.com releaser is based on TBDev,
originally by RedBeard of TorrentBits, extensively modified by
Gartenzwerg and Yuna Scatari.
Kinokpk.com releaser is free software;
you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Kinokpk.com is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Kinokpk.com releaser; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
MA  02111-1307  USA
Do not remove above lines!
*/

$starttime = explode(' ', microtime());
$starttime = $starttime[1] + $starttime[0];

define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './../../';
$phpEx = substr(strrchr(__FILE__, '.'), 1);

include($phpbb_root_path . 'common.' . $phpEx);
include($phpbb_root_path . 'includes/functions_display.' . $phpEx);

// Start session management
$user->session_begin();
$auth->acl($user->data);
$user->setup('posting');

header('Content-type: text/html; charset=UTF-8');

if(function_exists('iconv'))
{
	$poster_conv='iconv';
}
else if(function_exists('mb_convert_encoding'))
{
	$poster_conv='mb';
}
else
{
	exit('Sorry, not possible');
}

if(!$config['ppkbb_kpparser_enabled'])
{
	exit('Disabled');
}

if(!$user->data['is_registered'])
{
	exit('Guests not allowed');
}

$id=request_var('id', 0);
$filmname=request_var('filmname', '');
$kp_confirm=request_var('confirm', 0);
$p=request_var('p', '');
$kproot_image_dir='tracker/kinopoisk/images/';
$kpposters_image_dir='tracker/kinopoisk/images/posters/';
$kpratings_image_dir='tracker/kinopoisk/images/ratings/';
$kpmpaa_image_dir='tracker/kinopoisk/images/mpaa/';
$kpcache_image_dir='tracker/kinopoisk/images/cache/';
$kpimdb_image=$kproot_image_dir.'imdb2.gif';
$cache_dir=$phpbb_root_path."cache/";
$tracker_url=generate_board_url();

!$id || !$filmname ? $kp_confirm=0 : '';
$ppkbb_kpparser_imageopt=my_split_config($config['ppkbb_kpparser_imageopt'], 5, 'my_int_val');
?>

<html>
<head>
<title>Поиск с помощью кинопоиск.ру</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<style>
.row1, .row1 td { background: #EFEFEF;}
.row2, .row2 td { background: #DEE3E7;}
</style>
</head>
<body bgcolor="#DEE3E7">
<p style="padding: 6px 8px 7px;text-align:center;color:#D5E4EC;font-weight:bold;background:#006699;">Поиск фильма на Kinopoisk.ru</p>

<?php
echo '<div style="text-align:center;width:100%;'.($kp_confirm ? '' : 'display:none;').'" id="kp_wait">Подождите ...</div><div id="kp_window" style="visibility:'.($kp_confirm ? 'hidden' : 'visible;').'">';

if(!$kp_confirm)
{
	if(!isset($_GET['id']) && !isset($_GET['filmname']))
	{
		echo '<table><tr><td>Введите название фильма:</td></tr><tr><td><form method="get" action="'.append_sid("{$phpbb_root_path}tracker/kinopoisk/parser.{$phpEx}").'"><input type="text" name="filmname" size="40"><input type="hidden" name="sid" value="'.$user->data['session_id'].'" />
	<input type="submit" value="Продолжить" />
	</form></td></tr>';
	}
}

include_once("Snoopy.class.{$phpEx}");
$page = new Snoopy;

$i_headers=array('HTTP_USER_AGENT'=>'User-Agent', 'HTTP_ACCEPT'=>'Accept', 'HTTP_ACCEPT_LANGUAGE'=>'Accept-Language', 'HTTP_ACCEPT_CHARSET'=>'Accept-Charset', 'HTTP_KEEP_ALIVE'=>'Keep-Alive', 'HTTP_CONNECTION'=>'Connection', 'HTTP_CACHE_CONTROL'=>'Cache-Control');//, 'HTTP_ACCEPT_ENCODING'=>'Accept-Encoding'
foreach($i_headers as $k => $v)
{
	if(isset($_SERVER[$k]))
	{
		$page->rawheaders[$v]=$_SERVER[$k];
	}
}
$ppkbb_kpparser_loginpass=my_split_config($config['ppkbb_kpparser_loginpass'], 2 , 'strval');
if($ppkbb_kpparser_loginpass[0] && $ppkbb_kpparser_loginpass[1])
{
	$page->cookies=array('forum_data[login]'=>$ppkbb_kpparser_loginpass[0], 'forum_data[reg_key]'=>$ppkbb_kpparser_loginpass[1]);
}

if (isset($_GET['filmname']) && $_GET['filmname']!='' && !isset($_GET['id']))
{
	$film = urlencode($_GET['filmname']);
	$filmsafe = htmlspecialchars($_GET['filmname']);
	#  $film = addslashes($film);
	$source=t_getcache("search_".md5($_GET['filmname']), $ppkbb_kpparser_imageopt[4]);
	if($source===FALSE)
	{
		$page->referer="http://s.kinopoisk.ru/";
		$page->fetch("http://s.kinopoisk.ru/index.php?first=no&kp_query=".urlencode($poster_conv=='iconv' ? iconv('utf-8', 'windows-1251', $_GET['filmname']) : mb_convert_encoding($_GET['filmname'], 'CP-1251', 'UTF-8')));
		$source = $page->results;
		$source=$poster_conv=='iconv' ? iconv('windows-1251', 'utf-8', $source) : mb_convert_encoding($source, 'UTF-8', 'CP-1251');
		t_recache("search_".md5($_GET['filmname']), $source);
	}

	if (!$source)
	{
		exit('[1] Error, nothing found!');
	}

	$searched = search($source, $film);
	if(!$searched)
	{
		//if(stristr($source, '<title>'.$film.'</title>')!==false)
		//{
			preg_match('#<link rel=\"canonical\" href=\"http://www\.kinopoisk\.ru:80/level/1/film/(\d+)/\" />#si', $source, $film_id);
			if(@$film_id[1])
			{
				header("Location: ".append_sid("{$phpbb_root_path}tracker/kinopoisk/parser.php?id={$film_id[1]}&filmname={$film}"));
				exit();
			}
		//}
		exit('Film not found!');
	}
	echo '<table><tr><td align="center"><b>Найденные по запросу "'.$filmsafe.'" фильмы</b></td></tr>';
	foreach ($searched as $searchedrow)
	{
		preg_match('#"\?(id=\d+)"#si', $searchedrow, $match);
		if(@$match[1])
		{
			$searchedrow=str_replace('?'.$match[1], append_sid("{$phpbb_root_path}tracker/kinopoisk/parser.{$phpEx}", $match[1]."&amp;filmname=".urlencode($_GET['filmname'])), $searchedrow);
			echo "<tr><td>".$searchedrow."</td></tr>";
		}
	}
}
else if (isset($_GET['id']) && $_GET['id'] != '')
{
	if (!is_numeric($_GET['id']))
	{
		exit('Wrong ID');
	}
	$id = $_GET['id'];

	$source=t_getcache("film_".$id, $ppkbb_kpparser_imageopt[4]);
	if($source===FALSE)
	{
		$page->referer="http://s.kinopoisk.ru/index.php?first=no&kp_query=".urlencode($_GET['filmname']);
		$page->fetch("http://www.kinopoisk.ru/level/1/film/{$id}/");
		$source = $page->results;
		$source=$poster_conv=='iconv' ? iconv('windows-1251', 'utf-8', $source) : mb_convert_encoding($source, 'UTF-8', 'CP-1251');
		t_recache("film_".$id, $source);
	}

	if (!$source)
	{
		exit('[2] Error, nothing found!');
	}

	$dublers=$imdbimg='';
	$rusname = clear(get_content($source, 'rusname'));
	$origname = clear(get_content($source, 'origname'));
	$country = clear(get_content($source, 'country'));
	$year = clear(get_content($source, 'year'));
	$director = clear(get_content($source, 'director'));
	$genre = clear(get_content($source, 'genre'));
	$scenario = clear(get_content($source, 'scenario'));
	$producer = clear(get_content($source, 'producer'));
	$operator = clear(get_content($source, 'operator'));
	$budget = clear(get_content($source, 'budget'));
	$premieraworld = clear(get_content($source, 'premieraworld'));
	$mpaarating = clear(get_content($source, 'mpaa'));
	$mpaapic = $mpaarating;
	$imdbrating = clear(get_content($source, 'imdb'));
	$time = clear(get_content($source, 'time'));
	$top250 = clear(get_content($source, 'top250'));
	$descr = clear(get_content($source, 'descr'));
	$actors = substr(format_actors(get_content($source, 'actors')), 0, -2);
	$dublers=$dublers ? $dublers : '';

	if($kp_confirm)
	{
		if($ppkbb_kpparser_imageopt[0])
		{
			$m_time=0;
			if($ppkbb_kpparser_imageopt[4])
			{
				$m_time=@filemtime("{$phpbb_root_path}{$kpratings_image_dir}{$id}.gif");
			}
			if(!file_exists("{$phpbb_root_path}{$kpratings_image_dir}{$id}.gif") || ($m_time && time()-$m_time > $ppkbb_kpparser_imageopt[4]*86400))
			{
				@copy("http://www.kinopoisk.ru/rating/{$id}.gif", "{$phpbb_root_path}{$kpratings_image_dir}{$id}.gif");
			}
			if($imdbrating)
			{
				preg_match("#(\d+\.\d+) \(([\s0-9]+)\)#si", $imdbrating, $imdbs);
				if($imdbs[1] && $imdbs[2])
				{
					$imdbimg=file_exists($phpbb_root_path.$kpratings_image_dir."imdb{$id}.gif") ? true : false;
					$m_time=0;
					if($ppkbb_kpparser_imageopt[4])
					{
						$m_time=@filemtime($phpbb_root_path.$kpratings_image_dir."imdb{$id}.gif");
					}
					if(!$imdbimg || ($m_time && time()-$m_time > $ppkbb_kpparser_imageopt[4]*86400))
					{
						$imdbimg=imdb_rating($id, $imdbs[1], $imdbs[2]);
					}
					$imdbimg ? $imdbrating="[img]{$tracker_url}/{$kpratings_image_dir}imdb{$id}.gif[/img]" : '';
				}
			}
		}
	}

	$kinopoiskrating = $ppkbb_kpparser_imageopt[0] ? "[url=http://www.kinopoisk.ru/level/1/film/{$id}/][img]{$tracker_url}/{$kpratings_image_dir}{$id}.gif[/img][/url]" : "[url=http://www.kinopoisk.ru/level/1/film/{$id}/][img]http://www.kinopoisk.ru/rating/{$id}.gif[/img][/url]";
	$poster = get_poster($id);

	switch ($mpaarating)
	{
		case "G": $mpaarating = "[img]{$tracker_url}/{$kpmpaa_image_dir}G.gif[/img] G - Нет возрастных ограничений"; break;
		case "PG": $mpaarating ="[img]{$tracker_url}/{$kpmpaa_image_dir}PG.gif[/img] PG - Рекомендуется присутствие родителей"; break;
		case "PG-13": $mpaarating = "[img]{$tracker_url}/{$kpmpaa_image_dir}PG-13.gif[/img] PG-13 - Детям до 13 лет просмотр не желателен"; break;
		case "R": $mpaarating = "[img]{$tracker_url}/{$kpmpaa_image_dir}R.gif[/img] R - Лицам до 17 лет обязательно присутствие взрослого"; break;
		case "NC-17": $mpaarating = "[img]{$tracker_url}/{$kpmpaa_image_dir}NC-17.gif[/img] NC-17 - Лицам до 17 лет просмотр запрещен"; break;
	}

	echo '
	<script type="text/javascript" language="javascript">
	function fillform()
	{
		'.($kp_confirm ? 'formfill("addit", "'.$kinopoiskrating.'", "Рейтинг Kinopoisk");
		formfill("imdb", "'.($imdbimg ? $imdbrating : "[img]{$tracker_url}/{$kproot_image_dir}imdb.gif[/img] {$imdbrating}").'", "Рейтинг IMDB");
		formfill("addit", "'.$mpaarating.'", "Рейтинг MPAA");
		formfill("top250", "'.$top250.'", "Топ 250");
		formfill("addit", "'.$descr.'", "Описание");
		formfill("style", "'.$genre.'", "Жанр");
		formfill("addit", "'.$premieraworld.'", "Премьера в мире");
		formfill("addit", "'.$budget.'", "Бюджет");
		formfill("addit", "'.$scenario.'", "Сценарий");
		formfill("addit", "'.$producer.'", "Продюсер");
		formfill("time", "'.$time.'", "Продолжительность");
		formfill("land", "'.$country.'", "Страна производства");
		formfill("addit", "'.$dublers.'", "Роли дублировали");
		formfill("acters", "'.$actors.'", "В ролях");
		formfill("producer", "'.$director.'", "Режиссер");
		formfill("year", "'.$year.'", "Год выхода");
		formfill("orig", "'.$origname.'", "Оригинальное название");
		formfill("addit", "'.$rusname.'", "Русское название");
		formfill("poster", "'.$poster.'", "Постер");
		self.close();' : 'var str="'.append_sid("{$phpbb_root_path}tracker/kinopoisk/parser.{$phpEx}", "confirm=1").'";
		str=str.replace("&amp;", "&");
		document.location.href=str+"&id="+'.$id.'+"&filmname='.urlencode($_GET['filmname']).'&p="+(document.getElementById("kp_img") ? document.kp_img.kp_i.value : "");').'
	}
	function formfill(field, value, rvalue)
	{
		if(!value)
		{
			return;
		}

		if(field=="top250")
		{
			rvalue = "[color=#FF0000]"+rvalue+"[/color]";
			value = "[url=http://www.kinopoisk.ru/level/20/#"+value+"][color=#FF0000][b]#"+value+"[/b][/color][/url]";
		}

		/*if(window.opener.document.getElementById(field)!=null)
		{
			window.opener.document.forms["postform"].elements[field].value = value;
		}
		else
		{*/
			if(field!="poster")
			{
				window.opener.document.forms["postform"].elements["message"].value ="[b]"+rvalue+"[/b]: "+ value+"\r\n"+window.opener.document.forms["postform"].elements["message"].value;
			}
			else
			{
				window.opener.document.forms["postform"].elements["message"].value ="[ImgRight]"+value+"[/ImgRight] "+"\r\n"+window.opener.document.forms["postform"].elements["message"].value;
			}
		//}
	}
	</script>
	';

	if(!$kp_confirm)
	{
		echo "<table width=\"100%\" >
		".($ppkbb_kpparser_imageopt[3] ? "<tr><td>Постер:</td><td><img src=\"{$tracker_url}/{$kproot_image_dir}no_poster.gif\" /></td></tr>" : '')."
		<!-- <tr><td>Постер:</td><td>$poster</td></tr> -->
		<tr><td>Русское название:</td><td>$rusname</td></tr>
		<tr><td>Оригинальное название:</td><td>$origname</td></tr>
		<tr><td>В ролях:</td><td>$actors</td></tr>
		<tr><td>Роли дублировали:</td><td>$dublers</td></tr>
		<tr><td>Страна производства:</td><td>$country</td></tr>
		<tr><td>Жанр:</td><td>$genre</td></tr>
		<tr><td>Продолжительность:</td><td>$time</td></tr>
		<tr><td>Год выхода:</td><td>$year</td></tr>
		<tr><td>Премьера в мире:</td><td>$premieraworld</td></tr>
		<tr><td>Топ 250:</td><td>$top250</td></tr>
		<tr><td>IMDB:</td><td>$imdbrating</td></tr>
		<tr><td>Кинопоиск:</td><td>$kinopoiskrating</td></tr>
		<tr><td>Рейтинг MPAA:</td><td>$mpaarating</tr>
		<tr><td>Режиссер:</td><td>$director</td></tr>
		<tr><td>Продюсер:</td><td>$producer</td></tr>
		<tr><td>Описание:</td><td>$descr</td></tr>";

		echo '<tr>
		<td align="center" colspan="2">
		<input type="button"  value="Закрыть окно" onclick="javascript:window.close();">&nbsp;
		<input type="button"  value="Заполнить форму" onclick="javascript:fillform();">
		</td></tr>
		';
	}
}
?>

</table>

<?php
if(!$kp_confirm)
{
	echo '<p align="center"><input type="button" value="Повторить поиск" OnClick=\'self.location.href="'.append_sid("{$phpbb_root_path}tracker/kinopoisk/parser.{$phpEx}").'";\'></p>';
}
else
{
	/*if($id)
	{
		t_cleancache("poster_l1$id");
		t_cleancache("poster_l2$id");
		t_cleancache("film_".$id);
	}
	isset($_GET['filmname']) ? t_cleancache("search_".md5($_GET['filmname'])) : '';*/
	echo '<script type="text/javascript" language="javascript">
		fillform();
	</script>';
}
?>
</div>
</body>
</html>

<?php
$mtime = explode(' ', microtime());
$totaltime = $mtime[0] + $mtime[1] - $starttime;

//############################################################

function clear($text)
{
	$text=utf8_normalize_nfc($text);
	$text = preg_replace("#\t|\r|\x0B|\n#si","", strip_tags($text));
	$text = preg_replace("#&nbsp;#si"," ", $text);
	$text = str_replace(', ...', '', $text);
	//$text = preg_replace("#\n(.*?)\n#si","\n",$text);
	$text = preg_replace(array("#&\#133;|&\#151;#si", "#&(l|r)aquo;#si"), array("", "'"), $text);
	return $text;
}

function format_actors($text)
{
	global $dublers;

	//<span itemprop="actors"><a href="/level/4/people/17733/">Сэм Уортингтон</a></span>
	preg_match_all("#<span itemprop=\"actors\"><a.*?>(.*?)</a></span>#si", $text, $actors);
	$actor_string='';
	$stop = count($actors[1]) - 1;
	for ($i = 0; $i < $stop; $i++)
	{
		$actor_string .= ( ( $actor_string != '' ) ? ', ' : '' ) . $actors[1][$i];
	}
	if(strstr($actor_string, '...'))
	{
		$actor_string=explode(', ..., ', $actor_string);
		$dublers=@$actor_string[1];
		$actor_string=$actor_string[0];
	}
	return $actor_string.'';
}

function format_dublers($text)
{
	preg_match_all("#<a.*?>(.*?)</a>#si", $text, $dublers);
	$dubler_string='';
	$stop = count($dublers[1]);
	for($i=0;$i<$stop;$i++)
	{
		$dubler_string.=($dubler_string!= '' ? ', ' : '').$dublers[1][$i];
	}
	return $dubler_string.'';
}

function search($source, $text)
{
	$result=false;
	$searchfilms="#<p class=\"name\"><a href=\"(?:http://www.kinopoisk.ru)?/level/1/film/(.*?)a>#si";
	//$searchfilms2 = "#<font color=\"\#999999\">(.*?)</font>#si";
	#$searchfilms3 = "#e\">(.*?)</a></td>#is";

	while(preg_match_all($searchfilms, $source, $matches))
	{
		//preg_match_all($searchfilms2, $source, $matches2);
		#preg_match_all($searchfilms3, $source, $matches3);
		foreach ($matches as $key => $temparray)
		{
			foreach ($temparray as $key2 => $tempresult)
			{
				$result[$key2] = $tempresult;
				$result[$key2] = preg_replace("#(.*?)/sr/1/\">(.*?)</#is", "<a href=\"?id=\\1\">\\2</a>", $result[$key2]);//."   ".$matches2[$key][$key2];
			}
		}
		return $result;
	}
}

function get_poster($id)
{
	global $page, $phpbb_root_path, $kp_image_dir, $kproot_image_dir, $kpposters_image_dir, $tracker_url, $kp_confirm, $p, $ppkbb_kpparser_imageopt, $kpcache_image_dir, $poster_conv, $config;

	$s_poster=$poster=$posters_form='';
	$del_posters=array();

	$body=t_getcache("poster_l1{$id}", $ppkbb_kpparser_imageopt[4]);
	if($body===FALSE)
	{
		$page->referer="http://www.kinopoisk.ru/level/13/film/{$id}/";
		$page->fetch("http://www.kinopoisk.ru/level/17/film/{$id}/");
		$body = $page->results;
		$body=$poster_conv=='iconv' ? iconv('windows-1251', 'utf-8', $body) : mb_convert_encoding($body, 'UTF-8', 'CP-1251');
		t_recache("poster_l1{$id}", $body);
	}

	/*$pars = "/Location:\s(.*)\s/";
	preg_match_all($pars, $body, $matches, PREG_PATTERN_ORDER);
	if (isset($matches[1][0]))
	{
		$link = substr($matches[1][0], 1, strlen($matches[1][0])-2);
	}
	else
	{
		$link = "";
	}
	if ($link != "")
	{
		$body=t_getcache("poster_l2{$id}", $ppkbb_kpparser_imageopt[4]);
		if($body===FALSE)
		{
			$page->referer="http://www.kinopoisk.ru/level/17/film/{$id}/";
			$page->fetch("http://www.kinopoisk.ru/{$link}");
			$body = $page->results;
			$body = "";
			while ($line = fgets ($fp, 4096))
			{
				$body .= $line;
			}
			$body=iconv('windows-1251', 'utf-8', $body);
			$body=$poster_conv=='iconv' ? iconv('windows-1251', 'utf-8', $body) : mb_convert_encoding($body, 'UTF-8', 'CP-1251');
			t_recache("poster_l2$id", $body);
		}
	}*/
	$link=0;
	if(!preg_match("#Ни дня без нового постера!#si", $body))
	{
		$link=1;
		//<a href="/picture/1358119/"><img  src="http://st.kinopoisk.ru/images/poster/sm_1358119.jpg" width="170" height="130" alt="Просмотр фото" title="Просмотр постера" /></a>
		preg_match_all("#<a href=\"(/picture/([0-9]{1,10})/)\"><img(\s+class=\"new\")?\s+src=\"(?:.*?)/images/poster/([a-zA-Z0-9_]+\.jpg)\"#", $body, $matches, PREG_PATTERN_ORDER);
	}

	if($link && @$matches[1][0]!='' && @$matches[4][0]!='')
	{
		//if($kp_confirm && $p)
		//{
			foreach($matches[4] as $i => $posters)
			{
				$posters=basename($posters);
				if($ppkbb_kpparser_imageopt[3] && $i >= $ppkbb_kpparser_imageopt[3])
				{
					break;
				}
				if($ppkbb_kpparser_imageopt[3])
				{
					$m_time=0;
					if($ppkbb_kpparser_imageopt[4])
					{
						$m_time=@filemtime($phpbb_root_path.$kpcache_image_dir.$posters);
					}
					if(!file_exists($phpbb_root_path.$kpcache_image_dir.$posters) || ($m_time && time()-$m_time > $ppkbb_kpparser_imageopt[4]*86400))
					{
						@copy("http://www.kinopoisk.ru/images/poster/".$posters, $phpbb_root_path.$kpcache_image_dir.$posters);
					}
					$config['ppkbb_kpparser_cleancache']==2 ? $del_posters[]=$phpbb_root_path.$kpcache_image_dir.$posters : '';
				}

				$posters_form.= '<option value="'.$posters.'">'.$posters.'</option>';
				if($posters==$p)
				{
					$s_poster=$i;
					$poster=$p;
				}
			}
		//}
		$poster_form='
		<script type="text/javascript">
		// <![CDATA[
		function l_image()
		{
			if(document.kp_img.kp_i.value)
			{
				document.images[0].src = "'.$tracker_url.'/'.$kpcache_image_dir.'"+document.kp_img.kp_i.value;
			}
			else
			{
				document.images[0].src = "'.$tracker_url.'/'.$kproot_image_dir.'no_poster.gif";
			}
		}
		// ]]>
		</script>
		';
		$poster_form.= '<div style="text-align:center;width:100%;"><form id="kp_img" name="kp_img">Постер: <select name="kp_i"'.($ppkbb_kpparser_imageopt[3] ? ' onchange="l_image();"' : '').'><option value=""></option>';
		$poster_form.=$posters_form;
		$poster_form.= '</select></form></div>';

		if($kp_confirm)
		{
			if($poster && $ppkbb_kpparser_imageopt[1] && $ppkbb_kpparser_imageopt[2]==1)
			{
				$m_time=0;
				if($ppkbb_kpparser_imageopt[4])
				{
					$m_time=@filemtime($phpbb_root_path.$kpposters_image_dir.$poster);
				}
				if(!file_exists($phpbb_root_path.$kpposters_image_dir.$poster) || ($m_time && time()-$m_time > $ppkbb_kpparser_imageopt[4]*86400))
				{
					@copy("http://www.kinopoisk.ru/images/poster/".$poster, $phpbb_root_path.$kpposters_image_dir.$poster);
				}
			}
		}
		else
		{
			if($posters_form)
			{
				echo $poster_form;
			}
		}

		if($ppkbb_kpparser_imageopt[2]==1 && $poster)
		{
			if($ppkbb_kpparser_imageopt[1])
			{
				$poster = "{$tracker_url}/{$kpposters_image_dir}".$poster;
			}
			else
			{
				$poster = "http://www.kinopoisk.ru/images/poster/".$poster;
			}
		}

		if($s_poster!=='' && @$matches[1][$s_poster] && $ppkbb_kpparser_imageopt[2]!=1)
		{
			$source=t_getcache("poster_l3".md5($matches[1][$s_poster]), $ppkbb_kpparser_imageopt[4]);
			if($source===FALSE)
			{
				$page->referer="http://www.kinopoisk.ru/level/17/film/{$id}/";
				$page->fetch("http://www.kinopoisk.ru".$matches[1][$s_poster]);
				$source = $page->results;
				$source=$poster_conv=='iconv' ? iconv('windows-1251', 'utf-8', $source) : mb_convert_encoding($source, 'UTF-8', 'CP-1251');
				t_recache("poster_l3".md5($matches[1][$s_poster]), $source);
			}

			if($source)
			{
				//<img style="cursor: pointer;" id="image" src="http://st.kinopoisk.ru/im/poster/1/3/5/kinopoisk.ru-Avatar-1358119.jpg"
				preg_match_all('#<img style=\"cursor: pointer;\" id=\"image\" src=\"(.*?)\"#si', $source, $match);
				if(/*@$match[1][0] && */@$match[1][0])
				{
					preg_match('#([^/]+)$#', $match[1][0], $match2);
					if(@$match2[1])
					{
						if($kp_confirm && $ppkbb_kpparser_imageopt[1])
						{
							$m_time=0;
							if($ppkbb_kpparser_imageopt[4])
							{
								$m_time=@filemtime($phpbb_root_path.$kpposters_image_dir.$match2[1]);
							}
							if(!file_exists($phpbb_root_path.$kpposters_image_dir.$match2[1]) || ($m_time && time()-$m_time > $ppkbb_kpparser_imageopt[4]*86400))
							{
								@copy($match[1][0], $phpbb_root_path.$kpposters_image_dir.$match2[1]);
							}
						}
						//t_cleancache("poster_l3".md5($matches[1][$s_poster]));
						if($ppkbb_kpparser_imageopt[1])
						{
							$poster = "{$tracker_url}/{$kpposters_image_dir}".$match2[1];
						}
						else
						{
							$poster = $match[1][0];
						}
					}
				}
			}
		}
		if($kp_confirm && $del_posters)
		{
			foreach($del_posters as $d)
			{
				@unlink($d);
			}
		}
		return $poster;
	}
	else
	{
		return $poster;
	}
}

function get_content($text, $option)
{
	if ($option == 'rusname')
	{
		$search = "#<meta name=\"keywords\" content=\"(.*?)\(#si";
	}
	elseif ($option == 'origname')
	{
		$search = "#<meta name=\"keywords\" content=\".*?\((.*?)\)#si";
	}
	elseif ($option == 'country')
	{
/*
<tr>
    <td class="type"   >страна</td>

    <td class=""   >
        <div style="position: relative">
            <a href="/level/10/m_act%5Bcountry%5D/1/" >США</a>, <a href="/level/10/m_act%5Bcountry%5D/11/" >Великобритания</a>

        </div>
    </td>
</tr>
*/
		$search = "#<a href=\"/level/10/m_act%5Bcountry%5D/(?:\d+)/\"\s?>(?!<)(.*?)</a>#msi";
		//$parse=1;
	}
	elseif ($option == 'year')
	{
/*
<td class="type"   >год</td>
    <td class=""   >
        <div style="position: relative">
            <a href="/level/10/m_act%5Byear%5D/2009/" title="">2009</a>

        </div>

    </td>
*/
		/*$search = "#год</td><td(:?.*?)?>(.*?)</td>#si";*/
		$search = "#<a href=\"/level/10/m_act%5Byear%5D/(?:\d+)/\" title=\"(?:.*?)\">(?!<)(.*?)</a>#msi";
		//$parse = 1;
	}
	elseif ($option == 'director')
	{
		$search = "#режиссер</td><td(:?.*?)?>(.*?)</td>#si";
		//$parse = 1;
	}
	elseif ($option == 'slogan')
	{
		$search = "#слоган</td><td(:?.*?)?>(.*?)</td>#si";
		//$parse = 1;
	}
	elseif ($option == 'scenario')
	{
		$search = "#сценарий</td><td(:?.*?)?>(.*?)</td>#si";
		//$parse = 1;
	}
	elseif ($option == 'producer')
	{
		$search = "#продюсер</td><td(:?.*?)?>(.*?)</td>#si";
		//$parse = 1;
	}
	elseif ($option == 'operator')
	{
		$search = "#оператор</td><td(:?.*?)?>(.*?)</td>#si";
		//$parse = 1;
	}
	elseif ($option == 'budget')
	{
		$search = "#бюджет</td><td(:?.*?)?>(.*?)</td>#si";
		//$parse = 1;
	}
	elseif ($option == 'manyusa')
	{
		$search = "#сборы в США</td><td(:?.*?)?>(.*?)</td>#si";
		//$parse = 1;
	}
	elseif ($option == 'manyworld')
	{
		$search = "#сборы в мире</td><td(:?.*?)?>(.*?)</td>#si";
		//$parse = 1;
	}
	elseif ($option == 'manyrf')
	{
		$search = "#сборы в России</td><td(:?.*?)?>(.*?)</td>#si";
		//$parse = 1;
	}
	elseif ($option == 'premieraworld')
	{
/*
<td id="div_world_prem_td1" class="type" onmouseover="overPopupDiv('div_world_prem')" onmouseout="outPopupDiv('div_world_prem')" style="cursor: pointer">премьера (мир)</td>
            <td id="div_world_prem_td2" class="calendar" onmouseover="overPopupDiv('div_world_prem')" onmouseout="outPopupDiv('div_world_prem')" style="cursor: pointer">
                <div style="position: relative">
                    <a href="/level/80/film/251733/" title="">10 декабря 2009</a>

                    <s class="popup_help_icon"></s>
                </div>
            </td>

*/
		/*$search = '#премьера \(мир\)</td><td(:?.*?)?>(.*?)</td>#si';*/
		$search = "#<a href=\"/level/80/film/(?:\d+)/\" title=\"(?:.*?)\">(?!<)(.*?)</a>#msi";
		//$parse = 1;
	}
	elseif ($option == 'premierarf')
	{
		$search = '#премьера \(РФ\)</td><td(:?.*?)?>(.*?)</td>#si';
		//$parse = 0;
	}
	elseif ($option == 'time')
	{
		$search = '#время</td><td(:?.*?)?>(.*?)</td>#si';
		//$parse = 1;
	}
	elseif ($option == 'mpaa')
	{
/*

        <tr class="ratePopup" onmouseover="mpaaShow(this)" onmouseout="mpaaHide(this)">
            <td class="type">рейтинг MPAA</td>
            <td class="rate_pg13">

                    <a href="/level/38/film/251733/rn/PG-13/"><img src="http://st.kinopoisk.ru/images/mpaa/PG-13.gif" height="11" alt="рейтинг PG-13" border="0" /></a>

                <span>

                    детям до 13 лет просмотр не желателен

                </span>
            </td>
        </tr>
*/
		$search = "#<img src=\"(?:.*?)/images/mpaa/(.*?).gif\" height=\"11\" alt#si";
	}
	elseif ($option == 'imdb')
	{
		$search = "#>IMDB: (.*?)</div>#si";
	}
	elseif ($option == 'descr')
	{
		$search = "#_reachbanner_\">(.*?)</#si";
	}
	elseif ($option == 'kinopoisk')
	{
		$search = "#repeat-x; font-weight: normal !important; text-decoration: none\">(.*?)<span style=\"font:#si";
	}
	elseif ($option == 'kinopoisktotal')
	{
		$search = "#<span style=\"font:100 14px tahoma, verdana\">&nbsp;&nbsp;(.*?)</span>#si";
	}
	elseif ($option == 'actors')
	{
		$search = '#В главных ролях:(.*?)</table>#si';
	}
	elseif ($option == 'dublers')
	{
		$search = '#Роли дублировали(.*?)</table>#si';
	}
	elseif ($option == 'genre')
	{
		$search = "#жанр</td><td(:?.*?)?>(.*?)</td>#si";
		//$parse = 1;
	}
	elseif ($option == 'top250')
	{
		//<div class="div1"><span style="color: #007; font-size: 21px; position: absolute; top: 4px; left: 30px">Топ250: <a href="/level/20/#56" class="continue">56</a></span></div>
		$search = "#250: <a href=\"(.*?)\" class=\"continue\">(\d+)</a>#si";
		//$parse = 1;
	}

	$result=$multi=false;
	isset($parse) ? '' : $parse=false;

	if (!$parse)
	{
		$parse = 0;
	}
	if(in_array($option, array('country')))
	{
		$multi=true;
	}

	while (preg_match_all($search, $text, $matches))
	{
		foreach ($matches as $tempresult)
		{
			if($multi)
			{
				if(is_array($tempresult))
				{
					//echo $result;
					//var_dump($tempresult);
					foreach($tempresult as $v)
					{
						$r = preg_replace("#<a href=\"(.*?)>(.*?)</a>#is", "\\2", $v);
						$result .=($result ? ', ' : ''). str_replace(', ...', '', $r);
					}
				}
				break;
			}
			else
			{
				$result = $tempresult[$parse];
				if ($parse == 1)
				{
					$result = preg_replace("#<a href=\"(.*?)>(.*?)</a>#is", "\\2", $result);
					$result = str_replace(', ...', '', $result);
				}
			}
		}
		return $result;
	}
}

function t_recache($fname, $data)
{
	global $cache_dir, $phpEx;

	if(!$fname || !is_writable($cache_dir))
	{
		return FALSE;
	}

	$fname=basename($fname);
	$fn=$cache_dir.'data_ppkbb3cker_kpparser_'.$fname.'.'.$phpEx;
	$fo=@fopen($fn, 'wb');
	if($fo)
	{
		@flock($fo, LOCK_EX);
		@fwrite($fo, $data);
		//@fflush($fo);
		@flock($fo, LOCK_UN);
		@fclose($fo);

		phpbb_chmod($fn, CHMOD_READ);
	}
}

function t_getcache($t, $ctime=0)
{
	global $cache_dir, $phpEx;

	$data='';
	$t=basename($t);
	if(@file_exists($cache_dir.'data_ppkbb3cker_kpparser_'.$t.'.'.$phpEx))
	{
		if($ctime)
		{
			$m_time=@filemtime($cache_dir.'data_ppkbb3cker_kpparser_'.$t.'.'.$phpEx);
			if($m_time && time()-$m_time > $ctime*86400)
			{
				return FALSE;
			}
		}
		$data=file($cache_dir.'data_ppkbb3cker_kpparser_'.$t.'.'.$phpEx);
		return implode('', $data);
	}

	return FALSE;
}

function t_cleancache($t)
{
	global $cache_dir, $phpEx;

	$t=basename($t);
	if(@file_exists($cache_dir.'data_ppkbb3cker_kpparser_'.$t.'.'.$phpEx))
	{
		@unlink($cache_dir.'data_ppkbb3cker_kpparser_'.$t.'.'.$phpEx);
		return TRUE;
	}

	return FALSE;
}

function imdb_rating($id, $r, $v)
{
	global $phpbb_root_path, $kpimdb_image, $kpratings_image_dir;

	$r=number_format($r, 2, '.', '');
	//$v=number_format($v, 0, '', ' ');

	$im = @imagecreatefromgif($phpbb_root_path.$kpimdb_image);

	if(!$im)
	{
		return false;
	}

	$rating = imagecolorallocate($im, 153, 0, 0);
	imagestring($im, 5, 4, 5,  $r, $rating);

	$votes = imagecolorallocate($im, 0, 0, 0);
	imagestring($im, 1, 4, 25,  $v, $votes);

	imagegif($im, $phpbb_root_path.$kpratings_image_dir."imdb{$id}.gif");
	imagedestroy($im);

	return true;
}
?>
